package cn.tedu.ucenter.controller;

import cn.tedu.commonUtils.JwtUtils;
import cn.tedu.serviceBase.exception.EducationException;
import cn.tedu.ucenter.entity.Member;
import cn.tedu.ucenter.service.MemberService;
import cn.tedu.ucenter.utils.ConstantPropertiesUtil;
import cn.tedu.ucenter.utils.HttpClientUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;

@CrossOrigin
@RequestMapping("/api/ucenter/wx")
@Controller
public class WeiXinApiController {
    @Autowired
    private MemberService memberService;

    @GetMapping("/callback")
    public  String callback(String code,String state){
        String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                "?appid=%s" +
                "&secret=%s" +
                "&code=%s" +
                "&grant_type=authorization_code";

        String accessTokenUrl = String.format(baseAccessTokenUrl,
                ConstantPropertiesUtil.WX_OPEN_APP_ID,
                ConstantPropertiesUtil.WX_OPEN_APP_SECRET,
                code);

        String result = null;
        try {
            result = HttpClientUtils.get(accessTokenUrl);
            System.out.println("accessToken=============" + result);
        } catch (Exception e) {
            throw new EducationException(20001, "获取access_token失败");
        }
        Gson gson = new Gson();
        HashMap<String,String> map = gson.fromJson(result, HashMap.class);
        String accessToken = map.get("access_token");
        String openid = map.get("openid");
        LambdaQueryWrapper<Member> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Member::getOpenid,openid);
        wrapper.eq(Member::getIsDisabled,false);
        wrapper.eq(Member::getIsDeleted,false);
        Member one = memberService.getOne(wrapper);
        if (one == null) {
            //访问微信的资源服务器，获取用户信息
            String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                    "?access_token=%s" +
                    "&openid=%s";
            String userInfoUrl = String.format(baseUserInfoUrl, accessToken, openid);
            String resultUserInfo;
            try {
                 resultUserInfo = HttpClientUtils.get(userInfoUrl);
            } catch (Exception e) {
                e.printStackTrace();
                throw new EducationException(20001, "获取用户信息失败");
            }
            HashMap<String,String> userInfoMap = gson.fromJson(resultUserInfo,HashMap.class);
            String nickname = userInfoMap.get("nickname");
            String headimgurl = userInfoMap.get("headimgurl");
            one = new Member();
            one.setOpenid(openid);
            one.setNickname(nickname);
            one.setAvatar(headimgurl);
            memberService.save(one);
        }

// 生成jwt
        String token = JwtUtils.getJwtToken(one.getId(),one.getNickname());

//存入cookie
//CookieUtils.setCookie(request, response, "guli_jwt_token", token);

//因为端口号不同存在蛞蝓问题，cookie不能跨域，所以这里使用url重写
        return "redirect:http://localhost:3000?token=" + token;
    }

    @GetMapping("/login")
    public String getWxQrCode(){
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";

        // 回调地址
        String redirectUrl = ConstantPropertiesUtil.WX_OPEN_REDIRECT_URL; //获取业务服务器重定向地址
        try {
            redirectUrl = URLEncoder.encode(redirectUrl, "UTF-8"); //url编码
        } catch (UnsupportedEncodingException e) {
            throw new EducationException(20001, e.getMessage());
        }

        // 防止csrf攻击（跨站请求伪造攻击）
        //String state = UUID.randomUUID().toString().replaceAll("-", "");//一般情况下会使用一个随机数
        String state = "imhelen";//为了让大家能够使用我搭建的外网的微信回调跳转服务器，这里填写你在ngrok的前置域名
        System.out.println("state = " + state);

        // 采用redis等进行缓存state 使用sessionId为key 30分钟后过期，可配置
        //键："wechar-open-state-" + httpServletRequest.getSession().getId()
        //值：satte
        //过期时间：30分钟

        //生成qrcodeUrl
        String qrcodeUrl = String.format(
                baseUrl,
                ConstantPropertiesUtil.WX_OPEN_APP_ID,
                redirectUrl,
                state);

        return "redirect:" + qrcodeUrl;
    }
}
